package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.OrdersMapper;
import com.neusoft.elmboot.mapper.ScoreMapper;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.po.Score;
import com.neusoft.elmboot.service.ScoreService;
import com.neusoft.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ScoreServiceImpl implements ScoreService {

	@Autowired
	private ScoreMapper scoreMapper;

	@Autowired
	private OrdersMapper ordersMapper;

	// 清理过期积分
	public void removeExpiredScores(String userId) {
		List<Score> scores = scoreMapper.listScoreByUserId(userId);
		LocalDateTime now = LocalDateTime.now();

		scores.forEach(score -> {
			// 检查 deadLine 是否为空
			if (score.getDeadLine() != null && !score.getDeadLine().isEmpty()) {
				try {
					LocalDateTime deadLine = LocalDateTime.parse(score.getDeadLine(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
					if (deadLine.isBefore(now)) {
						removeScore(score.getScoreId());
					}
				} catch (Exception e) {
					System.out.println("解析日期失败，忽略此记录: " + score.getDeadLine());
				}
			}
		});
	}


	@Override
	public int useScore(Integer orderId, Integer usedScore) {
		Orders order = ordersMapper.getOrdersById(orderId);
		String userId = order.getUserId();

		// 插入一条新的负数积分记录，表示积分的扣除
		Score negativeScore = new Score();
		negativeScore.setUserId(userId);
		negativeScore.setOrderId(orderId);
		negativeScore.setScoreCount((double) -usedScore);  // 积分为负
		negativeScore.setCreateDate(null);  // 使用积分不需要创建日期
		negativeScore.setDeadLine(null);    // 使用积分不需要截止日期
		scoreMapper.saveScore(negativeScore);  // 保存负数积分记录

		// 如果没有使用积分（usedScore == 0），根据订单金额生成新的正积分
		if (usedScore == 0) {
			Double newScore = order.getOrderTotal();  // 1元=1积分
			if (newScore > 0) {
				Score positiveScore = new Score();
				positiveScore.setUserId(userId);
				positiveScore.setOrderId(orderId);
				positiveScore.setScoreCount(newScore);  // 积分为正
				createScore(positiveScore);  // 创建正积分记录
			}
		}

		return 1;  // 返回结果
	}

	@Override
	public int createScore(Score score) {
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime deadLine = now.plusDays(30);  // 积分有效期为30天
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

		score.setCreateDate(now.format(formatter));  // 设置创建日期
		score.setDeadLine(deadLine.format(formatter));  // 设置积分截止日期
		scoreMapper.saveScore(score);  // 保存积分记录

		return score.getOrderId();
	}

	@Override
	public int removeScore(Integer scoreId) {
		return scoreMapper.removeScore(scoreId);
	}

	@Override
	public List<Score> listScoreByUserId(String userId) {
		removeExpiredScores(userId);
		return scoreMapper.listScoreByUserId(userId).stream()
				.sorted((s1, s2) -> s2.getScoreId().compareTo(s1.getScoreId()))  // 按 scoreId 降序排序
				.limit(5)  // 只取前五条
				.peek(score -> {
					// 确保 createDate 和 deadLine 不为空
					if (score.getCreateDate() != null && !score.getCreateDate().isEmpty()) {
						score.setCreateDate(score.getCreateDate().substring(5, 10));
					} else {
						score.setCreateDate(""); // 或者根据需求设置默认值
					}

					if (score.getDeadLine() != null && !score.getDeadLine().isEmpty()) {
						score.setDeadLine(score.getDeadLine().substring(5, 10));
					} else {
						score.setDeadLine(""); // 或者根据需求设置默认值
					}
				})
				.collect(Collectors.toList());
	}


	@Override
	public int getAllScore(String userId) {
		return (int) scoreMapper.listScoreByUserId(userId).stream()
				.mapToDouble(Score::getScoreCount)
				.sum();
	}
}

